package com.xge.common_libary.view

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import me.drakeet.multitype.ItemViewBinder

abstract class BaseViewHolderLayoutBinder<T, VH : ViewHolder<T>>
    : ItemViewBinder<T, VH>() {
    override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): VH {
        val holder = onCreateViewHolderImpl(inflater, parent)
        // 检查是否是执行在ui线程
        if (Looper.myLooper() == Looper.getMainLooper()) {
            onViewHolderCreated(holder)
        } else {
            Handler(Looper.getMainLooper()).post {
                Runnable() {
                    kotlin.run {
                        onViewHolderCreated(holder)
                    }
                }
            }
        }
        return holder
    }

    abstract fun onCreateViewHolderImpl(inflater: LayoutInflater, parent: ViewGroup): VH

    protected open fun onViewHolderCreated(holder: VH) {}

    override fun onBindViewHolder(holder: VH, item:T & Any, payloads: List<Any>) {
        holder.item = item
        super.onBindViewHolder(holder, item, payloads)
    }
}

abstract class BaseLayoutBinder<T>(
    @LayoutRes private val layout: Int
) : BaseViewHolderLayoutBinder<T, ViewHolder<T>>() {

    override fun onCreateViewHolderImpl(inflater: LayoutInflater, parent: ViewGroup): ViewHolder<T> {
        return ViewHolder(inflater.inflate(layout, parent, false))
    }
}
